package com.android.aconportable;

//import javax.media.Buffer;
//import javax.media.Codec;
//import javax.media.Format;

import java.net.DatagramPacket;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

public class InComePacket {
	
	private UDPSocket socket;
	private boolean isPlaying = false;
	static final int frequency = 8000;
	static final int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
	static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
	private int playBufSize;
	private AudioTrack track;
	//private byte[] curBuf;
	//private byte[] preBuf;
	//private byte[] comBuf;
	private DatagramPacket packet;
	static final int bufsize = 1024;
	//private Codec codec;
	
	public InComePacket(UDPSocket socket){
		this.socket = socket;
		playBufSize = AudioTrack.getMinBufferSize(frequency,channelConfiguration, audioEncoding);
		track = new AudioTrack(AudioManager.STREAM_MUSIC, frequency,
				channelConfiguration, audioEncoding, playBufSize,
				AudioTrack.MODE_STREAM);
		
		System.out.println(playBufSize);
	}
	
	class OutComeThread extends Thread {
		public void run() {
			try {
				android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO);
				track.play();
				
				//javax.media.Buffer buffer = new Buffer();
				//javax.media.Buffer buffer2 = new Buffer();
				//codec.setOutputFormat(new Format(javax.media.format.AudioFormat.LINEAR, Format.byteArray));
				//codec.setInputFormat(new Format(javax.media.format.AudioFormat.GSM_RTP, Format.byteArray));
				
				
				while (isPlaying) {

					
					packet = socket.receive(playBufSize);
					//track.play();
					//buffer.setData(curBuf);
					//codec.process(buffer, buffer2);
					//System.out.println("good");
					//System.out.println(packet.getLength());
					//if(curBuf != preBuf)
					//track.write(curBuf,0,480);
					//track.write(curBuf, 0, curBuf.length);
					track.write(packet.getData(),0,1024);//packet.getLength());
					//System.out.println(socket.isConnect());
					//track.write((byte[])buffer2.getData(), 0, buffer2.getLength());
					//track.stop();
					//preBuf = curBuf;
				}
				// System.out.println("stop");
				
				
				//
				//track.stop();
			} catch (Throwable t) {
				// Toast.makeText(context, t.getMessage(), 1000);
			}
		}
	};
	
	public void play(){
		isPlaying = true;
		new OutComeThread().start();
	}
	
	public void stop(){
		isPlaying = false;
		track.stop();
		track.release();
		track = null;
	}
	
	public void setVolumn(float f1, float f2){
		track.setStereoVolume(f1, f2);
	}
}
